package com.hzjq.core.worker

import com.hzjq.core.bean.ErrorResult
import com.hzjq.core.callback.Callback
import com.hzjq.core.callback.OnCheckFirmwareStateCallback
import com.hzjq.core.callback.OnVersionCallback
import com.hzjq.core.callback.OnVersionUpgradeCallback
import com.hzjq.core.impl.VersionImpl
import com.hzjq.core.impl.VersionUpgradeImpl
import com.hzjq.core.serial.SerialManager
import com.hzjq.core.work.Work
import io.reactivex.functions.Consumer
import java.io.File

class CheckFirmwareStateWork : Work<Boolean> {

    private var firmwareVersion: Int = 0
    private lateinit var binFile: File
    private var checkCallback: OnCheckFirmwareStateCallback

    constructor(
        callback: Callback<Boolean>?,
        checkCallback: OnCheckFirmwareStateCallback
    ) : super(callback) {
        this.checkCallback = checkCallback
    }

    override fun cancel() {

    }

    override fun doWork(vararg args: Any) {
        firmwareVersion = args[0] as Int
        binFile = args[1] as File
        checkCallback.onProgressChanged(1,100,"正在检查固件")
        VersionImpl().getVersion(object : OnVersionCallback {
            override fun onResult(t: Int) {
                checkCallback.onCheckFirmwareUpgradeState(true)
            }

            override fun onRetryCountChanged(retryCount: Int, action: String) {

            }

            override fun onError(errorCode: ErrorResult) {
                if(errorCode.errorCode == -62) {
                    SerialManager.getInstance().enablePio(true)
                    doUpgrade()
                }
            }

        })
    }


    private fun doUpgrade() {
        VersionUpgradeImpl().onVersionUpgrade(firmwareVersion, binFile, object :
            OnVersionUpgradeCallback {
            override fun onProgressChanged(progress: Int, total: Int, action: String) {
                checkCallback.onProgressChanged(progress, total, action)
            }

            override fun onResult(t: Int) {
                checkCallback.onCheckFirmwareUpgradeState(true)
            }

            override fun onRetryCountChanged(retryCount: Int, action: String) {

            }

            override fun onError(errorCode: ErrorResult) {
                checkCallback.onCheckFirmwareUpgradeState(false)
            }

        })
    }
}